import json
import time
import traceback

from bs4 import BeautifulSoup
from selenium.webdriver.support.wait import WebDriverWait

import util


class Element:

    def get_price(self,soup):
        div = soup.find("div", class_="detail-header-data-box")
        print(div)
        if div is not None:
            divs = div.find_all("div", recursive=False)
            print(divs[0].div.span.text)
            print(divs[1].div.div.span.text)
    def get_items(self,driver,address):
        try:
            url = f"https://element.market/assets/zksync/{address}"
            driver.get(url)
            # time.sleep(4)
            util.wait(driver, self.__wait_detail_click)
            # driver.save_screenshot("test.png")
            html = driver.page_source
            soup = BeautifulSoup(html, 'html.parser')
            # get_price(soup)
            list = soup.find("div", class_="ReactVirtualized__Grid__innerScrollContainer")
            divs = list.find_all("div", recursive=False)
            print('列表item数目：', len(divs))
            sell_prices = []
            for div in divs:
                cdivs = div.div.find_all("div", recursive=False)
                item = {}
                btc_name_div = cdivs[1].find("div", class_="btc-asset-name-main")
                item['item'] = btc_name_div.div.text
                img = cdivs[3].find("img", class_="asset-card-market-icon")
                item['img'] = img['src']
                item['price'] = cdivs[3].div.button.div.text
                item['owner'] = cdivs[6].div.text
                sell_prices.append(item)
                # print("价格：" + cdivs[3].div.button.div.text)
                # print("所有者：" + cdivs[6].div.text)
            res_body = {
                "type": "sell_price",
                # "name": collection['name'],
                "contractAddress": address,
                # "data": json.dumps(sell_prices)
                "data": sell_prices
            }
            return res_body
        except Exception as e:
            print(e)
        return None

    def get_offers(self,driver,address):
        try:
            url = f"https://element.market/assets/zksync/{address}"
            driver.get(url + "?tag=offers")
            time.sleep(3)
            html = driver.page_source
            soup = BeautifulSoup(html, 'html.parser')
            divs = soup.find("div", class_="element-table-tbody")
            nodata = divs.find("div", class_="element-table-no-data")
            buy_prices = []
            if nodata is None:
                for div in divs:
                    item = {}
                    cdivs = div.find_all("div", recursive=False)
                    div = cdivs[0].find("div", class_="element-table-item-price-primary")
                    item['price'] = div.text
                    # print("价格："+ div.text)
                    div = cdivs[1].find("div", class_="element-table-item-price-primary semi")
                    item['size'] = div.text
                    # print("数量：" + div.text)
                    div = cdivs[2].find("div", class_="element-table-item-price-primary semi")
                    # print(div)
                    item['bidders'] = div.text
                    # print("报价人数：" + div.text)
                    buy_prices.append(item)
                return {"type": "buy_price", "data": buy_prices}
            else:
                # 没有报价,后面没有必要去查询详情了
                return
        except Exception as e:
            print(e)
            traceback.print_exc()
        return None

    def __wait_detail_page(self,driver):
        return driver.find_element_by_class_name("assets-detail-infos-head")

    def __wait_detail_click(self,driver):
        # print("wait_detail_click")
        # print(driver.find_element_by_class_name("element-table-no-data"))
        el = None
        try:
            el = driver.find_element_by_class_name("ReactVirtualized__Grid__innerScrollContainer")
        except Exception as e:
            pass
        if el is not None:
            # print("find el")
            return el
        print("return not find")
        return driver.find_element_by_class_name("element-table-no-data")

    def get_detail(self,url, driver=None):
        if driver is None:
            driver = util.get_chrome_html_driver(url)
        else:
            driver.get(url)
        print("get driver")
        # time.sleep(2)
        wait = WebDriverWait(driver, 10, 1);
        wait.until(self.__wait_detail_page, "wait fail!")
        # driver.save_screenshot("test1.png")
        div = driver.find_element_by_class_name("assets-detail-infos-head")
        divs = div.find_elements_by_tag_name("div")
        divs[1].click()
        # time.sleep(1)
        wait.until(self.__wait_detail_click, "wait fail!")
        html = driver.page_source
        soup = BeautifulSoup(html, 'html.parser')
        nodata = soup.find("div", class_="element-table-no-data")
        if nodata is not None:
            return []
        # driver.save_screenshot("test2.png")
        div = soup.find("div", class_="ReactVirtualized__Grid__innerScrollContainer")
        # print(div)
        divs = div.find_all("div", recursive=False)
        # print(divs)
        data = []
        if len(divs) > 1:
            divs = divs[1:]
            for div in divs:
                # print(div)
                cdivs = div.div.find_all("div", recursive=False)
                # print(cdivs)
                price = cdivs[1].find("div", class_="element-table-item-price-primary").text
                usd_price = cdivs[2].find("div", class_="element-table-item-price-primary semi").text
                cnt = cdivs[3].find("div", class_="element-table-item-price-primary semi").text
                over_due = cdivs[4].find("div", class_="element-table-item-price-primary semi").text
                user = cdivs[5].find("a").text
                # print(cdivs[5].find("a"))
                item = {}
                item['unit_price'] = price
                item['usd_unit_price'] = usd_price
                item['quantity'] = cnt
                item['expiration'] = over_due
                item['from'] = user
                data.append(item)
            print(data)
        return data
